import { Category } from '@libs/db/models/category.model';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class CategoryService {
  constructor(@InjectModel('Category') private readonly categoryModel: Model<Category>) { }
  // 查询所有新闻分类
  async findAllNewsCategory() {
    try {
      let res = await this.categoryModel.findOne({
        name: "动态"
      })
      const cates = await this.categoryModel.aggregate([
        {
          $match: { 'parent': res._id },
        },
        {
          $lookup: {
            from: 'categories',
            localField: '_id',
            foreignField: 'parent',
            as: 'children'
          }
        }
      ])
      return cates;
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  // 查找所有产品分类
  async findAllProdCategory() {
    try {
      let res = await this.categoryModel.findOne({
        name: "产品"
      })
      const cates = await this.categoryModel.aggregate([
        {
          $match: { 'parent': res._id },
        },
        {
          $lookup: {
            from: 'categories',
            localField: '_id',
            foreignField: 'parent',
            as: 'children'
          }
        },
        {
          $project: {
            label: "$name",
            value: "$_id",
            children: "$children"
          }
        }
      ])
      // 这样前端就不用处理了
      for (let i = 0; i < cates.length; i++) {
        let item = cates[i]
        let child = []
        for (let j = 0; j < item.children.length; j++) {
          child.push({
            label: item.children[j].name,
            value: item.children[j]._id
          })
        }
        item.children = child
      }
      return cates;
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  async getAllCategories() {
    try {
      const newsCategories = await this.findAllNewsCategory();
      const prodCategories = await this.findAllProdCategory();
      return {
        newsCategories,
        prodCategories
      }
    } catch (e) {
      if (e.status === 400) {
        throw new HttpException(e, HttpStatus.BAD_REQUEST)
      } else {
        throw new HttpException('服务器内部错误', HttpStatus.INTERNAL_SERVER_ERROR)
      }
    }
  }

  create(createCategoryDto: any) {
    return 'This action adds a new category';
  }

  findAll() {
    return `This action returns all category`;
  }

  findOne(id: number) {
    return `This action returns a #${id} category`;
  }

  update(id: number, updateCategoryDto: any) {
    return `This action updates a #${id} category`;
  }

  remove(id: number) {
    return `This action removes a #${id} category`;
  }
}
